<template>
  <div>
    <!-- <div class="list-table" style="margin-bottom:20px;">
      <el-switch
        v-model="cashflowQuarterOrMonth"
        :active-text="$t('按月统计')"
        :inactive-text="$t('按季统计')"
      />
      <cashflow ref="cashflow" :quarter-or-month="cashflowQuarterOrMonth" />
      <el-row class="cashflow">
        <el-col :span="4">
          <div class="">Gross IRR
            <el-tooltip placement="bottom">
              <div slot="content">
                {{ $t('根据现金流自动计算') }}<br>
                {{ $t('排除基金费用与基金管理费后，由所有参与IRR计算的现金流计算') }}<br>

              </div>
              <el-button class="tipText" type="text">
                <i class="el-icon-question" style="color: #595a5a;" />
              </el-button>
            </el-tooltip>
          </div>
          <div v-if="fundCashflowVO" class=""><el-link type="primary" @click="findIRR('fundGrossIrr')">{{ (fundCashflowVO.irr !== 0 && fundCashflowVO.irr !== null ? fundCashflowVO.irr: '-') }}</el-link></div>
        </el-col>
        <el-col :span="4">
          <div class="">Net IRR
            <el-tooltip placement="bottom">
              <div slot="content">
                {{ $t('根据现金流自动计算') }}<br>
                {{ $t('由所有参与IRR计算的现金流计算') }}<br>
              </div>
              <el-button class="tipText" type="text">
                <i class="el-icon-question" style="color: #595a5a;" />
              </el-button>
            </el-tooltip>
          </div>
          <div v-if="fundCashflowVO" class=""><el-link type="primary" @click="findIRR('netIrr')">{{ (fundCashflowVO.netIrr !== 0 && fundCashflowVO.netIrr !== null ? fundCashflowVO.netIrr: '-') }}</el-link></div>
        </el-col>
        <el-col :span="4">
          <div class="">DPI
            <el-tooltip placement="bottom">
              <div slot="content">
                {{ $t('出资人分配金额 / 出资人实缴金额') }}
              </div>
              <el-button class="tipText" type="text">
                <i class="el-icon-question" style="color: #595a5a;" />
              </el-button>
            </el-tooltip>
          </div>
          <div v-if="fundCashflowVO" class="">{{ (fundCashflowVO.dpi !== 0 && fundCashflowVO.dpi !== null ? fundCashflowVO.dpi: '-') }}</div>
        </el-col>
        <el-col :span="4">
          <div class="">TVPI
            <el-tooltip placement="bottom">
              <div slot="content">
                {{ $t('(基金分配总额＋基金最新估值) / 出资人实缴金额') }}
              </div>
              <el-button class="tipText" type="text">
                <i class="el-icon-question" style="color: #595a5a;" />
              </el-button>
            </el-tooltip>
          </div>
          <div v-if="fundCashflowVO" class="">{{ (fundCashflowVO.tvpi !== 0 && fundCashflowVO.tvpi !== null ? fundCashflowVO.tvpi: '-') }}</div>
        </el-col>
        <el-col :span="4">
          <div class="">RVPI
            <el-tooltip placement="bottom">
              <div slot="content">
                TVPI-DPI
              </div>
              <el-button class="tipText" type="text">
                <i class="el-icon-question" style="color: #595a5a;" />
              </el-button>
            </el-tooltip>
          </div>
          <div v-if="fundCashflowVO" class="">{{ (fundCashflowVO.rvpi !== 0 && fundCashflowVO.rvpi !== null ? fundCashflowVO.rvpi: '-') }}</div>
        </el-col>
        <el-col v-if="false" :span="4">
          <div class="">MOIC
            <el-tooltip placement="bottom">
              <div slot="content">
                {{ $t('流入现金流 / 流出现金流') }}
              </div>
              <el-button class="tipText" type="text">
                <i class="el-icon-question" style="color: #595a5a;" />
              </el-button>
            </el-tooltip>
          </div>
          <div v-if="fundCashflowVO" class="">{{ (fundCashflowVO.moic !== 0 && fundCashflowVO.moic !== null ? fundCashflowVO.moic: '-') }}</div>
        </el-col>
      </el-row>
    </div> -->
    <div class="list-table">
      <div class="area-header">
        <span class="area-header-title">{{ $t('基金现金流') }}</span>
      </div>
      <el-form ref="queryForm" :model="queryParams" :inline="true">
        <el-form-item label-width="150" :label="$t('现金流类型')" prop="type">
          <el-select v-model="queryParams.type" :placeholder="$t('现金流类型')" clearable>
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="$t(dict.dictLabel)"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="this.$route.query.id == null" :label="$t('基金名称')" prop="fundId">
          <MainBodySelect
            v-model="form.fundId"
            parameters="fund"
            disabled="true"
          />
        </el-form-item>
        <el-form-item :label="$t('发生时间')" prop="operateDate">
          <DatePicker
            v-model="operateDates"
            type="daterange"
          />
        </el-form-item>
        <el-form-item :label="$t('方向')" prop="direction">
          <el-select v-model="queryParams.direction" :placeholder="$t('方向')" clearable>
            <el-option
              v-for="dict in directionOptions"
              :key="dict.dictValue"
              :label="$t(dict.dictLabel)"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('业务类型')" prop="operateType">
          <el-select v-model="queryParams.operateType" :placeholder="$t('业务类型')" clearable>
            <el-option
              v-for="dict in operateTypeOptions"
              :key="dict.dictValue"
              :label="$t(dict.dictLabel)"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['fund:cashflow:edit']"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addHandle"
          >{{ $t("新增") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['fund:cashflow:export']"
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="exportHandle"
          >{{ $t("导出") }}</el-button>
        </el-col>
        <!--        <el-col :span="1.5">-->
        <!--          <el-button-->
        <!--            v-hasPermi="['deal:cashflow:view']"-->
        <!--            type="primary"-->
        <!--            icon="el-icon-info"-->
        <!--            size="mini"-->
        <!--            @click="getIrr"-->
        <!--          >{{ $t("获取IRR") }}</el-button>-->
        <!--        </el-col>-->
      </el-row>

      <el-table v-loading="loading" :data="fundCashflowList" border>
        <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
          <template slot-scope="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column v-if="this.$route.query.id == null" :label="$t('基金名称')" align="center" prop="fundName" />
        <el-table-column :label="$t('现金流类型')" align="center" prop="type" :formatter="typeFormat" />
        <el-table-column :label="$t('项目名称')" align="center" prop="dealName" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.dealName }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('业务类型')" align="center" prop="operateType" :formatter="operateTypeFormat" />
        <el-table-column :label="$t('权益变更时间')" align="center" prop="equityChangeTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.equityChangeTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('发生时间')" align="center" prop="operateDate" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.operateDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('币种')" align="center" prop="currency" :formatter="formatCurrencyDict" width="150" />
        <el-table-column :label="$t('发生金额') + $t('(元)')" align="center" prop="operateAmount" width="180">
          <template slot-scope="scope">
            <span class="money-text">{{ moneyFormat((scope.row.direction=== 'LC'? 0- scope.row.operateAmount: scope.row.operateAmount), undefined, 2, true) }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column :label="$t('汇率')" align="center" prop="exchangeRate" show-overflow-tooltip width="120">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ moneyFormat(scope.row.exchangeRate) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
          <template slot="header">
            <span>{{ $t('操作') }}</span>
            <!--            <el-tooltip placement="top">-->
            <!--              <div slot="content">-->
            <!--                {{ $t('不是从现金流功能添加的数据，不能修改与删除，如需修改请修改来源数据') }}-->
            <!--              </div>-->
            <!--              <i class="el-icon-question" />-->
            <!--            </el-tooltip>-->
          </template>
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['fund:cashflow:edit']"
              size="small"
              type="text"
              :icon="'el-icon-edit'"
              @click="updateHandle(scope.row)"
            >{{ $t('修改') }}</el-button>
            <el-button
              v-hasPermi="['fund:cashflow:remove']"
              size="small"
              type="text"
              icon="el-icon-delete"

              @click="deleteHandle(scope.row)"
            >{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改基金现金流对话框 -->
    <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <fundCashflowForm ref="fundCashflowForm" />
    </el-dialog>

    <!-- 现金流IRR对话框 -->
    <el-dialog :title="$t('IRR')" :visible.sync="irrOpen" :close-on-click-modal="false" width="550px" :lock-scroll="false" append-to-body>
      <div v-loading="irrLoading">
        <el-table :data="historyIrrList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('维度')" align="center" prop="dimension" width="259" />
          <el-table-column :label="$t('IRR')" align="center" prop="xirr" width="200" />
        </el-table>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listFundCashflow, delFundCashflow, getCashFlowCombined, getFundCashflowIrr, getFundIRRHistory } from '@/api/fund/cashflow/fundCashflow'
import fundCashflowForm from './fundCashflowForm.vue'
import MainBodySelect from '@/components/MainBodySelect'
import { downLoadExcel } from '@/utils/excelDownload'
// import cashflow from '@/views/chart/cashflow'
import { getFundBase } from '@/api/fund/fundBase'
import { getSystemCurrency } from '@/api/system/config'
export default {
  components: {
      fundCashflowForm,
      MainBodySelect
      // cashflow
  },
  data() {
      return {
        cashflowQuarterOrMonth: false,
        // 遮罩层
        loading: true,
        irrLoading: false,
        // 总条数
        total: 0,
        // 基金现金流表格数据
        fundCashflowList: [],
        // 基金现金流合计信息
        fundCashflowVO: {},
        fundCurr: '',
        defCurr: '',
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        formOpen: false,
        irrOpen: false,
        // 现金流类型  预计 实际字典
        typeOptions: [],
        // 方向：流入、流出字典
        directionOptions: [],
        // 类型：投资、回款、费用字典
        operateTypeOptions: [],
        // 是否参与IRR计算字典
        whetherIrrOptions: [],
        // 流入类型，收益，本金字典
        incomeTypeOptions: [],
        currencyOptions: [],
        historyIrrList: [],
        // 发生时间
        operateDates: [],
          // 查询参数
          queryParams: {
              type: undefined,
              fundId: this.$route.query.id,
              operateDate: undefined,
              direction: undefined,
              operateType: undefined,
              startDate: undefined,
              endDate: undefined,
              whetherIrr: 'Y',
              pageNum: 1,
              pageSize: 10
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
        type: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], fundId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateDate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateAmount: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], direction: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], whetherIrr: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], incomeType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], equityChangeTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ] }
      }
  },
  created() {
    this.initCurr()
      // 查询基金现金流合计信息
      this.getCashFlowCombined()

      this.getList()
      this.getDicts('cash_flow_type').then(response => {
          this.typeOptions = response.data
      })
      this.getDicts('cash_flow_direction').then(response => {
          this.directionOptions = response.data
      })
      this.getDicts('fund_cash_flow_type').then(response => {
          this.operateTypeOptions = response.data
      })
      this.getDicts('sys_yes_no').then(response => {
          this.whetherIrrOptions = response.data
      })
      this.getDicts('income_type').then(response => {
          this.incomeTypeOptions = response.data
      })
      this.getDicts('currency').then(response => {
        this.currencyOptions = response.data
      })
  },
  mounted() {
    this.load()
  },
  methods: {
    load() {
      if (this.$refs.cashflow?.getList !== undefined) {
        this.$refs.cashflow.getList()
      }
    },
    /** 查询基金现金流列表 */
    getList() {
        this.loading = true
        if (this.operateDates != null && this.operateDates.length > 0) {
          this.queryParams.startDate = this.operateDates[0]
          this.queryParams.endDate = this.operateDates[1]
        } else {
          this.queryParams.startDate = undefined
          this.queryParams.endDate = undefined
        }
        listFundCashflow(this.queryParams).then(response => {
            this.fundCashflowList = response.rows
            this.total = response.total
            this.loading = false
            this.load()
        })
    },
    disbtn(val) {
      if (val) {
        return true
      } else {
        return false
      }
    },
    // 现金流类型  预计 实际字典翻译
    typeFormat(row) {
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 方向：流入、流出字典翻译
    directionFormat(row) {
      return this.selectDictLabel(this.directionOptions, row.direction)
    },
    // 类型：投资、回款、费用字典翻译
    operateTypeFormat(row) {
      return this.selectDictLabel(this.operateTypeOptions, row.operateType)
    },
    // 是否参与IRR计算字典翻译
    whetherIrrFormat(row) {
      return this.selectDictLabel(this.whetherIrrOptions, row.whetherIrr)
    },
    // 流入类型，收益，本金字典翻译
    incomeTypeFormat(row) {
      return this.selectDictLabel(this.incomeTypeOptions, row.incomeType)
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            type: undefined,
            fundId: undefined,
            dataId: undefined,
            component: undefined,
            operateDate: undefined,
            equityChangeTime: undefined,
            operateAmount: undefined,
            direction: '0',
            operateType: undefined,
            whetherIrr: '0',
            incomeType: '0',
            remark: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.operateDates = undefined
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.title = this.$t('基金现金流')
        this.$nextTick(() => {
            this.$refs.fundCashflowForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.title = this.$t('基金现金流')
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.fundCashflowForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delFundCashflow(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        downLoadExcel('/cashflow/fundCashflow/export', this.addDateRange(this.queryParams, this.operateDates))
    },
    // 查询基金现金流合计
    getCashFlowCombined() {
      if (this.queryParams.fundId !== undefined) {
        getCashFlowCombined(this.queryParams.fundId).then(response => {
          this.fundCashflowVO = response.data
        })
      }
    },
    // 计算irr
    getIrr() {
      getFundCashflowIrr(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        let msg = ''
        if (res.data === 502) {
          msg = this.$t('计算失败：小于或等于一条现金流')
        } else if (res.data === 503) {
          msg = this.$t('计算失败：第一条现金流的时间不是最早时间')
        } else if (res.data === 504) {
          msg = this.$t('计算失败：第一条现金流的payment的值不为负')
        } else {
          msg = res.data
        }
        this.$alert(msg, '当前数据IRR', {
          dangerouslyUseHTMLString: true
        })
      })
    },
    formatCurrencyDict(row) {
      return this.formatCurrency(row.currency)
    },
    // 币种翻译
    formatCurrency(val) {
      const currency = this.currencyOptions.find(obj => obj.dictValue === val)
      if (currency) {
        return currency.dictLabel
      }
      return val
    },
    // 初始化币种信息
    async initCurr(val) {
      let param = this.$route.query.id
      if (this.$route.query.id === undefined) {
        param = val
      }
      await getFundBase(param).then(res => {
        this.fundCurr = res.data.currency
      })
      await getSystemCurrency().then(res => {
        if (res.code === 200) {
          this.defCurr = res.data
        } else {
          this.msgError(res.msg)
        }
      })
    },
    findIRR(type) {
      this.historyIrrList = []
      this.irrOpen = true
      this.irrLoading = true
      if (this.$route.query.id !== undefined) {
          getFundIRRHistory(this.$route.query.id, type).then(response => {
            this.historyIrrList = response.rows
          })
      }
      this.irrLoading = false
    }
  }
}
</script>
